<template>
  <a-layout>
    <a-layout-sider
      breakpoint="lg"
      collapsed-width="0"
      width="250"
      class="left-sider"
    >
      <a-tree
        :tree-data="treeData"
        :replaceFields="{
          title: 'name',
          key: 'uid',
        }"
        :style="htree"
        @select="onThingSelected"
      ></a-tree>
    </a-layout-sider>

    <a-layout-content style="margin: 0 0 0 5px">
      <a-form-model layout="inline">
        <a-form-model-item label="属性">
          <a-select
            style="width: 220px"
            v-model="currentPID"
            :labelInValue="true"
            @change="onPChanged"
          >
            <a-select-option
              v-for="item in properties"
              :key="item.identifier"
              :value="item.identifier"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>

          <a-select
            v-if="subProps && subProps.length > 0"
            style="width: 220px"
            v-model="subId"
          >
            <a-select-option
              v-for="item in subProps"
              :key="item.identifier"
              :value="item.identifier"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="条件">
          <a-range-picker
            :show-time="{ format: 'HH:mm' }"
            format="YYYY-MM-DD HH:mm"
            :placeholder="['开始时间', '结束时间']"
            @change="onChange"
            @ok="onOk"
          />
          <a-button :disabled="currentPID == null" @click="queryData"
            >查询</a-button
          >
        </a-form-model-item>
      </a-form-model>
      <a-tabs default-active-key="1" @change="onTypeChanged">
        <a-tab-pane tab="数据" key="1">
          <a-table
            :columns="columns"
            :data-source="datas"
            :row-key="
              (r, index) => {
                return index;
              }
            "
          >
            <div
              slot="filterDropdown"
              slot-scope="{
                setSelectedKeys,
                selectedKeys,
                confirm,
                clearFilters,
                column,
              }"
              style="padding: 8px"
            >
              <a-input
                v-ant-ref="(c) => (searchInput = c)"
                :placeholder="`Search ${column.dataIndex}`"
                :value="selectedKeys[0]"
                style="width: 188px; margin-bottom: 8px; display: block"
                @change="
                  (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
                "
                @pressEnter="
                  () => handleSearch(selectedKeys, confirm, column.dataIndex)
                "
              />
              <a-button
                icon="search"
                size="small"
                style="width: 90px; margin-right: 8px"
                @click="
                  () => handleSearch(selectedKeys, confirm, column.dataIndex)
                "
              >
                Search
              </a-button>
              <a-button
                size="small"
                style="width: 90px"
                @click="() => handleReset(clearFilters)"
              >
                Reset
              </a-button>
            </div>
            <a-icon
              slot="filterIcon"
              slot-scope="filtered"
              type="search"
              :style="{ color: filtered ? '#108ee9' : undefined }"
            />
            <template
              slot="customRender"
              slot-scope="text, record, index, column"
            >
              <span v-if="searchText && searchedColumn === column.dataIndex">
                <template
                  v-for="(fragment, i) in text
                    .toString()
                    .split(
                      new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i')
                    )"
                >
                  <mark
                    v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                    :key="i"
                    class="highlight"
                    >{{ fragment }}</mark
                  >
                  <template v-else>{{ fragment }}</template>
                </template>
              </span>
              <template v-else>
                {{ text }}
              </template>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane tab="曲线" key="2">
          <div id="chart" ref="chart" style="width: 600px; height: 460px"></div>
        </a-tab-pane>
      </a-tabs>
    </a-layout-content>
  </a-layout>
</template>
<script>
const columns = [
  {
    title: "值",
    dataIndex: "value",
  },
  {
    title: "采集时间",
    dataIndex: "picktime",
  },
  {
    title: "名称",
    dataIndex: "pn",
    key: "name",
  },

  {
    title: "子属性",
    dataIndex: "sname",
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender",
    },
    onFilter: (value, record) =>
      record.sname.toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => {
          this.searchInput.focus();
        });
      }
    },
  },
  {
    title: "索引",
    dataIndex: "pi",
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender",
    },
    onFilter: (value, record) =>
      record.pi.toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => {
          this.searchInput.focus();
        });
      }
    },
  },
];
let echarts = require("echarts");
console.log("----------------", echarts);
import { getRealData, getHistroyData } from "@/services/dataAPI";
export default {
  name: "DataHistroy",
  components: {},

  watch: {},
  computed: {
    htree() {
      let height = document.body.clientHeight - 140;
      return "min-height:" + height + "px;width:90%";
    },
    properties() {
      if (this.thing) {
        let model = this.thing.model;
        if (!model) {
          model = this.$store.state.tmodel.tmodelCache[this.thing.model_id];
        }
        if (model) {
          if (typeof model.body == "string") {
            let obody = JSON.parse(model.body);
            return obody.properties;
          }
          return this.thing.model.body.properties;
        }
      }
      return [];
    },
    treeData() {
      return this.$store.state.thingView.stationTree;
    },
  },
  mounted() {
    this.refresh();
  },
  data() {
    return {
      thing: {},
      datas: [],
      subProps: [],
      columns,
      currentPID: {},
      subProperties: [],
      dateRange: [],
      chart: null,
      //videoID: "",
      searchText: "",
      subId: "",
      uris: [],
      chartOption: {
        tooltip: {
          trigger: "axis", // 显示横坐标值
        },
      },
    };
  },
  methods: {
    getSubItems() {
      this.subId = "";
      if (this.currentPID && this.currentPID.key) {
        let property = this.properties.find((p) => {
          return p.identifier === this.currentPID.key;
        });
        if (property) {
          if (property.data_type.type === "struct") {
            return property.data_type.specs;
          }
          if (property.data_type.type === "array") {
            if (property.data_type.specs) {
              if (property.data_type.specs.item.type == "struct") {
                return property.data_type.specs.item.specs;
              }
            }
          }
        }
      }
      return [];
    },
    onPChanged() {
      this.subProps = this.getSubItems();
    },
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
    },
    onThingSelected(selectedKeys, { selected, node }) {
      console.log("selected--------", node);
      if (selected) {
        //let id = selectedKeys[0]
        //this.$store.dispatch("thingView/refreshActiveThing", node.dataRef.uid);
        this.thing = this.$store.state.thingView.thingCache[node.dataRef.uid];
        this.currentPID = {};
        this.subProps = [];
        this.subId = "";
      }
    },
    refresh() {
      this.$store.dispatch("tmodel/refreshTModels");
      this.$store.dispatch("thingView/refreshAllThings", {});
    },
    handleReset(clearFilters) {
      clearFilters();
      this.searchText = "";
    },
    initChart() {
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.chart);
      }
    },

    onTypeChanged(key) {
      if (key == "2") {
        let _this = this;
        setTimeout(() => {
          _this.initChart();
          _this.handleData(this.datas);
        }, 300);
      }
    },
    handleData(data) {
      this.datas = data;
      if (this.datas) {
        this.datas.sort((a, b) => {
          return a.pick_time - b.pick_time;
        });
      }
      if (this.chart) {
        this.initChart();
        let series = {};
        this.chartOption.xAxis = {
          type: "time",
          splitLine: {
            show: false,
          },
        };
        this.chartOption.yAxis = { type: "value" };
        data.forEach((element) => {
          let id =
            element.tid +
            "_" +
            element.pi +
            "_" +
            element.pid +
            "_" +
            element.sid;
          //element[id] = id
          if (!series[id]) {
            series[id] = {
              type: "line",
              data: [],
              name: element.pn + "#" + element.pi + "#" + element.sname,
            };
          }

          series[id].data.push([element.picktime, element.value]);
        });
        this.chartOption.series = [];
        this.chartOption.legend = { data: [] };
        for (let s in series) {
          this.chartOption.series.push({
            name: series[s].name,
            data: series[s].data,
            type: "line",
          });
          this.chartOption.legend.data.push(series[s].name);
        }
        this.chartOption.legend.data.sort((a, b) => {
          let al = a.length;
          let bl = b.length;
          return al == bl ? (a > b ? 1 : -1) : al - bl;
        });
        this.chartOption.series.sort((a, b) => {
          let al = a.name.length;
          let bl = b.name.length;
          return al == bl ? (a.name > b.name ? 1 : -1) : al - bl;
          //return a.name > b.name ? 1: -1
        });
        this.chart.setOption(this.chartOption);
      }
    },
    queryData() {
      this.getHistroyData();
    },
    queryRealData() {
      let _this = this;

      getRealData(this.thing.uid, this.currentPID.key, this.subId, -1).then(
        (data) => {
          //let series = {};
          _this.handleData(data);
        }
      );
    },
    getHistroyData() {
      let _this = this;

      getHistroyData(
        this.thing.uid,
        this.currentPID.key,
        this.subId,
        -1,
        this.dateRange[0],
        this.dateRange[1]
      ).then((data) => {
        _this.handleData(data);
      });
    },
    onChange(value, dateString) {
      this.dateRange = dateString;
      console.log("Selected Time: ", value);
      console.log("Formatted Selected Time: ", dateString);
    },
    onOk(value) {
      console.log("onOk: ", value);
    },
  },
};
</script>
<style  lang="less" scoped>
.ant-tree li .ant-tree-node-content-wrapper{
    height:auto;
    }
    .ant-tree-node-content-wrapper{
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    max-width: 90%;
    }
</style>

